<template>
  <BasicDrawer v-bind="$attrs" @register="register" :title="displayModuleTitle" width="80%">
    <a-spin :spinning="isLoading" tip="正在加载单元信息..." size="large">
      <a-tabs v-model:activeKey="activeKey" v-if="unitInfoData.unitid">
        <a-tab-pane key="1" tab="基本信息">
          <a-row style="padding: 0 5px">
            <a-col :span="12" style="border-right: 1px solid #ddd; padding: 0 5px">
              <!--    基本信息组件-只负责基本信息        -->
              <UnitBasicInfoView :unit="unitInfoData" />
              <!--   文字轮播组件 -独立负责文字轮播         -->
              <TextSwiper :textItems="textStaticList" title-font-weight="bold" height="300px" />
            </a-col>
            <a-col :span="12" style="padding: 0 5px">
              <ImageSwiper :image-items="pictureStaticList" height="300px" />
              <!-- 地图 -->
              <div id="container"></div>
            </a-col>
          </a-row>
        </a-tab-pane>
        <a-tab-pane key="2" tab="全景图" v-if="vrpictureStaticList.length > 0">
          <div style="display: flex; flex-direction: row; flex-wrap: wrap; align-items: center">
            <a-button
              v-for="(item, index) in vrpictureStaticList"
              @click="currentVrPhotoId = item.id"
              :type="currentVrPhotoId == item.id ? 'primary' : ''"
              style="margin: 10px 10px 10px 0"
              >{{ item.title }}</a-button
            >
          </div>
          <div v-for="(item, index) in vrpictureStaticList">
            <template v-if="currentVrPhotoId == item.id">
              <PhotoPreview
                :photo="getImageFileUrlPrefix + item.url"
                height="calc(100vh - 200px)"
                :maxFov="110"
                :minFov="50"
              />
            </template>
          </div>
        </a-tab-pane>
        <a-tab-pane key="3" tab="危险源空间分布图" v-if="unitInfoData.bgimg?.id">
          <UnitHazardSvgView
            mode="allInfo"
            :svgData="unitInfoData.bgimg?.id"
            :key="unitInfoData.bgimg?.id"
          />
        </a-tab-pane>
      </a-tabs>

      <div v-else style="min-height: 400px; padding: 50px"> </div>
    </a-spin>
  </BasicDrawer>
</template>

<script lang="ts">
  import { defineComponent, ref, unref, computed, reactive, onMounted } from 'vue';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { QrCode, QrCodeActionType } from '/@/components/Qrcode/index';
  import { OperationTypeEnum } from '/@/enums/appEnum';
  import { QcUnifyTransToChildProps } from '/#/QcUnify';
  import { getUnitDivision, queryUnitStaticInfo } from '/@/api/ehs/unitDivision';
  import { displayTitle } from '/@/utils/QcUnifyUtil';
  import { queryEnumOptions } from '/@/api/platform/enum';
  import { useGlobSetting } from '/@/hooks/setting';
  const { globalProjectCode } = useGlobSetting();
  import PhotoPreview from '/@/components/QuCheng/PanoramicPreview/PhotoPreview.vue';
  import UnitHazardSvgView from './UnitHazardSvgView.vue';
  import { queryUnitCategory } from '/@/api/ehs/unitCategory';
  import AMapLoader from '@amap/amap-jsapi-loader';
  import { QrcodeOutlined, LeftOutlined, RightOutlined } from '@ant-design/icons-vue';
  import { getImageFileApi } from '/@/api/platform/file';
  import UnitBasicInfoView from '/@/views/ehs/unitDivision/UnitBasicInfoView.vue';

  // 导入新的 UnifiedSwiper 组件
  import ImageSwiper from '/@/components/QuCheng/Swiper/ImageSwiper.vue';
  import TextSwiper from '/@/components/QuCheng/Swiper/TextSwiper.vue';

  export default defineComponent({
    name: 'UnitBasicInfoDrawer',
    emits: ['register', 'success'],
    components: {
      TextSwiper,
      ImageSwiper,
      UnitBasicInfoView,
      BasicDrawer,
      PhotoPreview,
      UnitHazardSvgView,
      QrCode,
      QrcodeOutlined,
      LeftOutlined,
      RightOutlined,
    },
    setup() {
      let map = null;
      const qrRef = ref<Nullable<QrCodeActionType>>(null);
      const qcUnifyProps = ref<QcUnifyTransToChildProps>();
      const { uploadUrl } = useGlobSetting();
      const getImageFileUrlPrefix = ref<string>(uploadUrl + getImageFileApi);
      const dataId = ref();
      const activeKey = ref('1');
      const unitInfoData = ref({});
      // 所有单元分类信息
      const categoryData = ref();
      // 静态信息中的文字信息
      const textStaticList = ref([]);
      // 静态信息中的图片信息
      const pictureStaticList = ref([]);
      // 静态信息中的全景图信息
      const vrpictureStaticList = ref([]);
      // 当前展示的全景图的id
      const currentVrPhotoId = ref('');
      const projectCode = ref<String>(globalProjectCode);

      const isLoading = ref(false);

      /**
       * 单元二维码下载
       */
      function download() {
        const qrEl = unref(qrRef);
        if (!qrEl) return;
        qrEl.download(unitInfoData.value.unitname);
      }

      /**
       * 过滤出数据对应的枚举类label
       */
      function deepFilter(obj, option, findField1, findField2) {
        for (let i = 0; i < option.length; i++) {
          let a = option[i];
          if (a[findField2] == obj[findField1]) {
            return a;
          } else {
            if (a.children && a.children.length > 0) {
              let res = deepFilter(obj, a.children, findField1, findField2);
              if (res && res !== '-') {
                return res;
              }
            }
          }
        }
        return '-';
      }
      const [register, { closeDrawer, changeLoading }] = useDrawerInner(async (data) => {
        clearAllData();
        if (data != undefined && data != null) {
          isLoading.value = true;
          let unrefData = unref(data);
          qcUnifyProps.value = unrefData;
          dataId.value = data.dataId;
          activeKey.value = '1';

          try {
            //1.确保分类数据已加载
            if (!categoryData.value) {
              const categoryRes = await queryUnitCategory();
              categoryData.value = categoryRes;
            }

            //2.再加载单元数据
            const res = await getUnitDivision(data.dataId);

            //3.处理分类显示
            let uccdDisplay = null;
            if (res.uccd && categoryData.value) {
              const foundCategory = deepFilter(res, categoryData.value, 'uccd', 'uccd');
              uccdDisplay = foundCategory !== '-' ? foundCategory.ucnm : `未知分类(${res.uccd})`;
            }

            if (res.uccd && categoryData.value) {
              const foundCategory = deepFilter(res, categoryData.value, 'uccd', 'uccd');
              uccdDisplay = foundCategory !== '-' ? foundCategory.ucnm : `未知分类(${res.uccd})`;
            }

            unitInfoData.value = {
              ...res,
              bgimg: res.bgimg ? JSON.parse(res.bgimg) : null,
              uccd: uccdDisplay,
            };

            initMap();

            console.log('所有分类数据:', categoryData.value);
            console.log('完整分类数据:', JSON.stringify(categoryData.value, null, 2));

            const staticRes = await queryUnitStaticInfo(data.dataId);
            textStaticList.value = staticRes
              ? staticRes
                  .filter((item) => item.infotype == 1)
                  .map((el) => ({
                    content: el.content,
                    title: el.title,
                    id: el.id,
                  }))
              : [];
            pictureStaticList.value = staticRes
              ? staticRes
                  .filter((item) => item.infotype == 2)
                  .map((el) => ({
                    url: JSON.parse(el.content).url,
                    title: el.title,
                    id: el.id,
                  }))
              : [];
            vrpictureStaticList.value = staticRes
              ? staticRes
                  .filter((item) => item.infotype == 4)
                  .map((el) => ({
                    url: JSON.parse(el.content).url,
                    title: el.title,
                    id: el.id,
                  }))
              : [];
            currentVrPhotoId.value = vrpictureStaticList.value[0]?.id;
          } catch (ex) {
            console.log('加载数据失败:', ex);
          } finally {
            // 🔥 接口调用完成，隐藏 loading（无论成功还是失败）
            isLoading.value = false;
          }
        }
      });
      function clearAllData() {
        console.log('清空数据开始');

        // 🔥 重置加载状态
        isLoading.value = false;
        // 清空基本数据
        unitInfoData.value = {};
        dataId.value = null;
        activeKey.value = '1';

        // 清空静态信息列表
        textStaticList.value = [];
        pictureStaticList.value = [];
        vrpictureStaticList.value = [];
        currentVrPhotoId.value = '';

        // 清空地图（如果存在）
        if (map) {
          try {
            map.destroy();
            map = null;
          } catch (e) {
            console.warn('地图销毁失败:', e);
          }
        }

        // 重置其他状态
        qcUnifyProps.value = null;

        console.log('数据清空完成');
      }

      let displayModuleTitle = computed(() => {
        return displayTitle(qcUnifyProps.value);
      });
      function initMap() {
        window._AMapSecurityConfig = {
          securityJsCode: 'b12155c9eaece05da4c33dccb2b2d49b',
        };
        AMapLoader.load({
          key: '5dcdc2ec80646a4ef80755af9e92b0fb', // 申请好的Web端开发者Key，首次调用 load 时必填
          version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
          plugins: [], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
        })
          .then((AMap) => {
            map = new AMap.Map('container', {
              // 设置地图容器id
              viewMode: '2D', // 是否为3D地图模式
              zoom: unitInfoData.value.longitude && unitInfoData.value.latitude ? 12 : 10, // 初始化地图级别
              center:
                unitInfoData.value.longitude && unitInfoData.value.latitude
                  ? [unitInfoData.value.longitude, unitInfoData.value.latitude]
                  : [102.833669, 24.88149], // 初始化地图中心点位置
              mapStyle: 'amap://styles/normal',
            });
            let marker = new AMap.Marker({
              position:
                unitInfoData.value.longitude && unitInfoData.value.latitude
                  ? new AMap.LngLat(unitInfoData.value.longitude, unitInfoData.value.latitude)
                  : new AMap.LngLat(102.833669, 24.88149), // 经纬度对象，也可以是经纬度构成的一维数组[102.833669,24.88149]
              title: unitInfoData.value.unitname,
            });
            // 将创建的点标记添加到已有的地图实例：
            map.add(marker);
          })
          .catch((e) => {
            console.log(e);
          });
      }

      // 新增：合并轮播数据的计算属性
      const swiperData = computed(() => {
        const combined = [];

        // 将所有文字信息合并为一个项目
        if (textStaticList.value.length > 0) {
          combined.push({
            type: 'unitInfo', // 正确的类型
            id: 'unit-basic-info',
            title: unitInfoData.value.unitname || '单元信息',
            unit: unitInfoData.value, // 添加 unit 字段
            textInfos: textStaticList.value, // 正确的字段名
          });
        }

        // 添加图片信息
        pictureStaticList.value.forEach((item) => {
          combined.push({
            type: 'image',
            id: item.id,
            url: item.url,
            title: item.title,
          });
        });
        return combined;
        // 添加全景图信息
      });

      onMounted(() => {
        // 获取单元分类
        queryUnitCategory()
          .then((res) => {
            categoryData.value = res;
          })
          .catch((e) => {});
      });
      return {
        qrRef,
        textStaticList,
        pictureStaticList,
        vrpictureStaticList,
        currentVrPhotoId,
        getImageFileUrlPrefix,
        download,
        register,
        activeKey,
        dataId,
        displayModuleTitle,
        qcUnifyProps,
        categoryData,
        unitInfoData,
        deepFilter,
        swiperData,
        isLoading,
      };
    },
  });
</script>

<style scoped lang="less">
  p {
    font-size: 16px;
  }

  .h1Title {
    font-size: 25px;
    font-weight: 700;
    text-align: left;
    letter-spacing: 2px;
    margin: 10px 5px 10px 0;
  }

  .h2Title {
    font-size: 20px;
    font-weight: 700;
    text-align: left;
    letter-spacing: 2px;
    margin: 10px 5px 10px 0;
  }

  #container {
    padding: 0px;
    margin: 0px;
    width: 100%;
    height: 250px;
    margin: 20px 0 10px 0;
  }

  /* 轮播图的图片的高度为轮播区域高度(20rem)减去上下的边距(合计1rem) */
  @swipper-img-height: 20rem-1rem;

  .ant-carousel :deep(.slick-slide) {
    height: @swipper-img-height;
    line-height: @swipper-img-height;
    background: #fefefe;
    overflow: hidden;
  }

  .ant-carousel :deep(.slick-arrow.custom-slick-arrow) {
    width: 25px;
    height: 25px;
    font-size: 25px;
    color: #fff;
    opacity: 0.5;
    z-index: 1;
  }

  .ant-carousel :deep(.custom-slick-arrow:before) {
    display: none;
  }

  .ant-carousel :deep(.custom-slick-arrow:hover) {
    opacity: 0.8;
  }

  .ant-carousel :deep(.slick-slide h3) {
    color: #ffffff;
  }

  //轮播图缩放样式
  .relative {
    width: 100%;
    height: 300px;
  }

  .relativdive {
    width: 100%;
    height: 300px;
  }

  .swipper-img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  .loading-container {
    padding: 60px 20px;
    text-align: center;
    min-height: 400px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .loading-placeholder {
    width: 100%;
    background: #f5f5f5;
    border-radius: 6px;
  }
</style>
